import os
import requests
import tkinter as tk
from tkinter import scrolledtext, messagebox
from tkinter.ttk import Progressbar
import threading

# 函数：检查多个 Docker 镜像源的可用性
def check_docker_registry(urls, result_var, progress_var):
    success_results = []  # 存储成功访问镜像源的地址
    failure_results = []  # 存储无法访问镜像源的地址
    url_list = urls.split("\n")
    total_urls = len(url_list)
    for i, url in enumerate(url_list):
        url = url.strip()
        if not url:
            continue
        try:
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                success_results.append(url)
                result = f"{url} - 可访问\n"
            else:
                failure_results.append(url)
                result = f"{url} - 状态码: {response.status_code}\n"
        except requests.exceptions.RequestException:
            failure_results.append(url)
            result = f"{url} - 无法访问\n"

        # 更新结果变量
        result_var.set(result_var.get() + result)
        # 更新进度条
        progress_var.set((i + 1) / total_urls * 100)

    success_message = "以下镜像源地址可访问：\n\n" + "\n".join(success_results)
    failure_message = "以下镜像源地址不可访问：\n\n" + "\n".join(failure_results)
    final_result = success_message + "\n\n" + failure_message
    result_var.set(final_result)

# 安装必要的库
def install_requirements():
    try:
        import requests
    except ImportError:
        print("requests 库未安装，正在安装...")
        os.system("pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple/")

install_requirements()

# 创建主窗口
root = tk.Tk()
root.title("Docker 镜像源检查器")
root.geometry("800x600")  # 设置初始窗口大小
root.resizable(True, True)  # 允许调整窗口大小

# 输入框
url_input = scrolledtext.ScrolledText(root, width=60, height=15)
url_input.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)
url_input.insert(tk.END, "请输入每个 URL，并以换行符分隔")

# 进度条
progress = Progressbar(root, orient=tk.HORIZONTAL, length=300, mode='determinate')
progress.pack(pady=10, padx=10, fill=tk.X, expand=True)

# 结果文本框
result_output = scrolledtext.ScrolledText(root, width=60, height=15, state='disabled')
result_output.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)

# 按钮
check_button = tk.Button(root, text="检查", command=lambda: start_check())
check_button.pack(pady=5, padx=10, fill=tk.X, expand=True)

# 进度变量
progress_var = tk.DoubleVar()
progress['variable'] = progress_var

# 结果变量
result_var = tk.StringVar()
result_output.config(state='normal')
result_output.insert(tk.END, "")
result_output.config(state='disabled')

# 开始检查
def start_check():
    urls = url_input.get("1.0", tk.END).strip()
    if not urls:
        messagebox.showwarning("警告", "请输入至少一个有效的URL")
        return
    
    # 清空结果文本框
    result_output.config(state='normal')
    result_output.delete(1.0, tk.END)
    result_output.config(state='disabled')
    
    # 重置进度条
    progress_var.set(0)
    progress.pack(fill=tk.X, expand=True)  # 显示进度条

    # 在单独的线程中执行检查
    def check_thread():
        check_docker_registry(urls, result_var, progress_var)
        # 检查完成后隐藏进度条
        progress.pack_forget()
        # 使结果文本框可编辑
        result_output.config(state='normal')
        result_output.delete(1.0, tk.END)
        result_output.insert(tk.END, result_var.get())
        result_output.config(state='normal')  # 保持可编辑状态

    thread = threading.Thread(target=check_thread)
    thread.start()

# 运行主循环
root.mainloop()
